package com.ating.demo.Service;

import cn.hutool.core.util.StrUtil;
import com.ating.demo.Entity.Dto;
import com.ating.demo.Entity.Employee;
import com.ating.demo.Exceptiom.CustomException;
import com.ating.demo.Mapper.EmployeeMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class EmployeeService {

    @Resource
    private EmployeeMapper employeeMapper;

    public List<Employee> selectAll(Employee employee){
        return employeeMapper.selectAll(employee);
    }

    public Employee selectOne(Integer id){
        return employeeMapper.selectById(id);
    }

    public PageInfo<Employee> selectPage(Integer PageSize,Integer PageNum,Employee employee){
        PageHelper.startPage(PageNum,PageSize);
        List<Employee> list = employeeMapper.selectAll(employee);
        return PageInfo.of(list);
    }

    public void add(Employee employee){
        String username = employee.getUsername();
        Employee employee1 = employeeMapper.selectByUsername(username);
        //如果账号存在
        if(employee1 != null){
            throw new CustomException("500","账号已存在");
        }
        //如果密码没填
        if(StrUtil.isBlank((employee.getPassword()))){
            employee.setPassword("123");
        }
        //如果名字没填
        if(StrUtil.isBlank(employee.getName())){
            employee.setName(employee.getUsername());
        }
        employee.setRole("EMP");
        employeeMapper.insert(employee);
    }

    public void moveById(Integer id){
        employeeMapper.moveById(id);
    }

    public void update(Employee employee){
        employeeMapper.updateById(employee);
    }

    public Employee login(Dto dto){
        String username = dto.getUsername();
        Employee employee1 = employeeMapper.selectByUsername(username);
        //先查询用户在不在
        if(employee1 == null){
            throw new CustomException("500","查询不到该用户");
        }
        //查询密码正不正确
        String password = dto.getPassword();
        if(!employee1.getPassword().equals(password)){
            throw new CustomException("500","账号或密码错误");
        }
        return employee1;
    }

    public void register(Employee employee){
        add(employee);
    }
}
